package test;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class APIDemo2 {

    public static Connection connection = null;
    public static Admin admin = null;

    static {
        try {
            //配置信息
            Configuration conf = HBaseConfiguration.create();
            conf.set("hbase.zookeeper.quorum", "master,slave1,slave2");
            //创建连接对象
            connection = ConnectionFactory.createConnection(conf);
            //创建Admin对象
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void close() {

        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (admin != null) {
            try {
                admin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**************DDL**************/
    //判断表是否存在
    public static boolean isTableExist(String tableName) throws IOException {
        boolean result = admin.tableExists(TableName.valueOf(tableName));
        return result;

    }

    //创建表
    public static void createTable(String tableName, String... columnFamilys) throws IOException {
        //判断是否存在列族信息
        if (columnFamilys.length <= 0) {
            System.out.println("请设置列族信息！");
            return;
        }
        //判断表是否已经存在
        if (isTableExist(tableName)) {
            System.out.println("该表已存在！");
            return;
        }
        //创建表描述器
        HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
        //循环添加列族信息
        for (String columnFamily : columnFamilys) {
            //创建列族描述器
            HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(columnFamily);
            //添加列族信息
            hTableDescriptor.addFamily(hColumnDescriptor);
        }

        //创建表
        admin.createTable(hTableDescriptor);
    }

    //删除表
    public static void dropTable(String tableName) throws IOException {
        //判断表是否存在
        if (!isTableExist(tableName)) {
            System.out.println(tableName + "不存在！");
            return;
        }
        //使表下线
        admin.disableTable(TableName.valueOf(tableName));
        //删除表
        admin.deleteTable(TableName.valueOf(tableName));

    }

    //创建命名空间
    public static void createNameSpace(String nameSpace) {
        //创建命名空间描述器
        NamespaceDescriptor namespaceDescriptor = NamespaceDescriptor.create(nameSpace).build();
        //创建命名空间
        //因为官方没有提供判断命名空间是否存在的方法，所以要自己写trycatch抓一下命名空间已存在的异常
        try {
            admin.createNamespace(namespaceDescriptor);
        } catch (NamespaceExistException e) {
            System.out.println("命名空间已存在！");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**************DML**************/
    //向表插入数据
    public static void putData(String tableName, String rowKey, String cf, String cn, String value) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tableName));
        Put put = new Put(Bytes.toBytes(rowKey));
        put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn), Bytes.toBytes(value));
        table.put(put);
        table.close();
    }

    //获取表数据（get）
    //可以只输入rowkey(就不用add信息，直接遍历打印)
    //输入rowkey,cf(addFamliy)
    //输入rowkey,cf,cn(addcolumn)
    public static void getData(String tableName, String rowKey, String cf, String cn) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tableName));
        Get get = new Get(Bytes.toBytes(rowKey));
        get.addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn));
        //设置获取的最大版本数 默认是有几个版本就输出几个，也可以指定输出几个
        get.setMaxVersions();
        Result result = table.get(get);
        //解析result并打印
        for (Cell cell : result.rawCells()) {
            System.out.println("CF:" + Bytes.toString(CellUtil.cloneFamily(cell)) +
                    "CN:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +
                    "Value" + Bytes.toString(CellUtil.cloneValue(cell)));
        }
        table.close();
    }

    //获取表数据（scan）
    public static void scanTable(String tableName) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tableName));
        Scan scan = new Scan();
        ResultScanner resultScanner = table.getScanner(scan);
        for (Result result : resultScanner) {
            for (Cell cell : result.rawCells()) {
                System.out.println("CF:" + Bytes.toString(CellUtil.cloneFamily(cell)) +
                        "CN:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +
                        "Value" + Bytes.toString(CellUtil.cloneValue(cell)));
            }
        }
        table.close();

    }

    //删除表数据
    public static void deleteData(String tableName, String rowKey, String cf, String cn) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tableName));
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        table.delete(delete);
        table.close();
    }

    public static void main(String[] args) throws IOException {

        //1.查看表是否存在
        System.out.println(isTableExist("stu01"));
        //2.创建表
        createTable("stu01", "info1");
        //3.删除表
        dropTable("stu01");
        System.out.println(isTableExist("stu01"));
        //关闭资源
        close();
    }
}
